package com.example.yian.controller;
import com.example.yian.entity.User;
import com.example.yian.service.WeChatAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/login")
public class WeChatAuthController {

    @Autowired
    private WeChatAuthService weChatAuthService;

    @PostMapping
    public Map<String, Object> login(@RequestBody Map<String, String> requestBody) {
        String code = requestBody.get("code");
        Map<String, Object> response = new HashMap<>();
        Optional<User> userOptional = weChatAuthService.login(code);
        if (userOptional.isPresent()) {
            User user = userOptional.get();
            String token = user.getToken();
            response.put("code", 200);
            response.put("msg", "成功");
            response.put("data", Map.of("token", token));
        } else {
            response.put("code", 400);
            response.put("msg", "登录失败");
            response.put("time", Instant.now().toEpochMilli());
            response.put("data", new HashMap<>());
        }
        return response;
    }
}
